package com.spring.dynamicdatasource.utils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * JDBC工具
 *
 * @author houkunlin
 * @date 2019/9/10 下午9:05
 */
public class JdbcUtils {
    public static List<Map<String, Object>> resultSetToMaps(ResultSet resultSet) throws Exception {
        return resultSetToMaps(resultSet, ResultSetMetaData::getColumnName);
    }

    public static List<Map<String, Object>> resultSetToMaps(ResultSet resultSet, ExceptionBiFunction<ResultSetMetaData, Integer, String> function) throws Exception {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map;
        ResultSetMetaData metaData = resultSet.getMetaData();
        int len = metaData.getColumnCount();

        while (resultSet.next()) {
            map = new LinkedHashMap<>();
            for (int i = 1; i <= len; i++) {
                map.put(function.apply(metaData, i), resultSet.getObject(i));
            }
            list.add(map);
        }
        return list;
    }
}
